package com.pipe.protocol.events.table.reader;

import com.pipe.util.MyBytebufUtil;
import com.sun.scenario.effect.impl.prism.PrImage;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Kiven
 * @see <a>https://dev.mysql.com/doc/internals/en/myisam-column-attributes.html<a/>
 */
public class MysqlTypeVarcharReader implements ColumnReader<String>{
    private Logger log = LoggerFactory.getLogger(MysqlTypeVarcharReader.class);
    /**
     *  In MySQL 5.0 the length may be either 1 byte (for up to 255) or 2 bytes (for 256 to 65535).
     */
    private static int ONE_BYTE_MAX_LENGTH = 256;

    @Override
    public String read(ByteBuf byteBuf, int readLength) {
        log.debug("parse varchar!");
        int length = 0;
        if (readLength < ONE_BYTE_MAX_LENGTH){
            length = byteBuf.readUnsignedByte();
        } else {
            length = byteBuf.readUnsignedShortLE();
        }
        byte[] strArr = new byte[length];
        byteBuf.readBytes(strArr);
        return new String(strArr);
    }
}